package com.thoughtservice.jspdoc.utils;

/*
 * The contents of this file are subject to the Mozilla Public
 * License Version 1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 *
 * The Original Code is "JSP Documentation Generator Project".
 *
 */

import java.util.zip.*;
import java.io.*;

/**
 * Class to create ZIP files
 *
 * @author Jochen Luell (jochen@luell.com)
 */
public class Zipper {
	private ZipOutputStream zipStream = null;
	private FileOutputStream out = null;
	
	/**
	 * Constructor
	 * Opens the ZIP file.
	 *
	 * @param filePath java.lang.String FQN of output file
	 */
	public Zipper(String filePath) {
		try {
		   out = new FileOutputStream(filePath);
		   zipStream = new ZipOutputStream(out);
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Closs ZIP file
	 *
	 */
	public void finish() {
		try {
		        zipStream.finish();
		        out.close();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Adds a file to ZIP archive
	 *
	 * @param dir java.lang.String Name of directory the file resides in
	 * @param file java.lang.String Name of file to add
	 */
	public void addFile(String dir, String file) {
		try {
			FileInputStream in = new FileInputStream(dir + File.separator + file);
			ZipEntry ze = new ZipEntry(file);
			zipStream.putNextEntry(ze);
			
			int read = 0;
			byte[] buf = new byte[4 * 1024];
			
			while((read = in.read(buf)) != -1) {
				zipStream.write(buf, 0, read);
			}

			zipStream.closeEntry();
			in.close();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * Adds a string to ZIP archive
	 *
	 * @param text java.lang.String Text to add to ZIP archive
	 * @param file java.lang.String Name of file text should be saved in
	 */
	public void addText(String text, String file) {
		try {
			ZipEntry ze = new ZipEntry(file);
			zipStream.putNextEntry(ze);
			
			int read = 0;
			byte[] buf = text.getBytes();
			
			zipStream.write(buf, 0, buf.length);

			zipStream.closeEntry();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}
			
}
